3 * Contain classes for dealing with individual log entries
5 * This is how I see the log system history:
6 * - appending to plain wiki pages
7 * - formatting log entries based on database fields
8 * - user is now part of the action message
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 * @author Niklas Laxström
27 * @license GPL-2.0-or-later
31 use MediaWiki\Linker\LinkTarget
;
32 use MediaWiki\User\UserIdentity
;
33 use Wikimedia\Rdbms\IDatabase
;
36 * Interface for log entries. Every log entry has these methods.
47 public function getType();
54 public function getSubtype();
57 * The full logtype in format maintype/subtype.
61 public function getFullType();
64 * Get the extra parameters stored for this message.
68 public function getParameters();
71 * Get the user for performed this action.
75 public function getPerformer();
78 * Get the target page of this action.
82 public function getTarget();
85 * Get the timestamp when the action was executed.
89 public function getTimestamp();
92 * Get the user provided comment.
96 public function getComment();
99 * Get the access restriction.
103 public function getDeleted();
106 * @param int $field One of LogPage::DELETED_* bitfield constants
109 public function isDeleted( $field );
113 * Extends the LogEntryInterface with some basic functionality
117 abstract class LogEntryBase
implements LogEntry
{
119 public function getFullType() {
120 return $this->getType() . '/' . $this->getSubtype();
123 public function isDeleted( $field ) {
124 return ( $this->getDeleted() & $field ) === $field;
128 * Whether the parameters for this log are stored in new or
133 public function isLegacy() {
138 * Create a blob from a parameter array
141 * @param array $params
144 public static function makeParamBlob( $params ) {
145 return serialize( (array)$params );
149 * Extract a parameter array from a blob
152 * @param string $blob
155 public static function extractParams( $blob ) {
156 return unserialize( $blob );
161 * A value class to process existing log entries. In other words, this class caches a log
162 * entry from the database and provides an immutable object-oriented representation of it.
166 class DatabaseLogEntry
extends LogEntryBase
{
169 * Returns array of information that is needed for querying
170 * log entries. Array contains the following keys:
171 * tables, fields, conds, options and join_conds
175 public static function getSelectQueryData() {
176 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
177 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
179 $tables = array_merge(
180 [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ]
183 'log_id', 'log_type', 'log_action', 'log_timestamp',
184 'log_namespace', 'log_title', // unused log_page
185 'log_params', 'log_deleted',
186 'user_id', 'user_name', 'user_editcount',
187 ] +
$commentQuery['fields'] +
$actorQuery['fields'];
190 // IPs don't have an entry in user table
191 'user' => [ 'LEFT JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
192 ] +
$commentQuery['joins'] +
$actorQuery['joins'];
199 'join_conds' => $joins,
204 * Constructs new LogEntry from database result row.
205 * Supports rows from both logging and recentchanges table.
207 * @param stdClass|array $row
208 * @return DatabaseLogEntry
210 public static function newFromRow( $row ) {
212 if ( isset( $row->rc_logid
) ) {
213 return new RCDatabaseLogEntry( $row );
215 return new self( $row );
220 * Loads a LogEntry with the given id from database
223 * @param IDatabase $db
224 * @return DatabaseLogEntry|null
226 public static function newFromId( $id, IDatabase
$db ) {
227 $queryInfo = self
::getSelectQueryData();
228 $queryInfo['conds'] +
= [ 'log_id' => $id ];
229 $row = $db->selectRow(
230 $queryInfo['tables'],
231 $queryInfo['fields'],
234 $queryInfo['options'],
235 $queryInfo['join_conds']
240 return self
::newFromRow( $row );
243 /** @var stdClass Database result row. */
247 protected $performer;
249 /** @var array Parameters for log entry */
252 /** @var int A rev id associated to the log entry */
253 protected $revId = null;
255 /** @var bool Whether the parameters for this log entry are stored in new or old format. */
258 protected function __construct( $row ) {
263 * Returns the unique database id.
267 public function getId() {
268 return (int)$this->row
->log_id
;
272 * Returns whatever is stored in the database field.
276 protected function getRawParameters() {
277 return $this->row
->log_params
;
280 public function isLegacy() {
281 // This extracts the property
282 $this->getParameters();
283 return $this->legacy
;
286 public function getType() {
287 return $this->row
->log_type
;
290 public function getSubtype() {
291 return $this->row
->log_action
;
294 public function getParameters() {
295 if ( !isset( $this->params
) ) {
296 $blob = $this->getRawParameters();
297 Wikimedia\
suppressWarnings();
298 $params = LogEntryBase
::extractParams( $blob );
299 Wikimedia\restoreWarnings
();
300 if ( $params !== false ) {
301 $this->params
= $params;
302 $this->legacy
= false;
304 $this->params
= LogPage
::extractParams( $blob );
305 $this->legacy
= true;
308 if ( isset( $this->params
['associated_rev_id'] ) ) {
309 $this->revId
= $this->params
['associated_rev_id'];
310 unset( $this->params
['associated_rev_id'] );
314 return $this->params
;
317 public function getAssociatedRevId() {
318 // This extracts the property
319 $this->getParameters();
323 public function getPerformer() {
324 if ( !$this->performer
) {
325 $actorId = isset( $this->row
->log_actor
) ?
(int)$this->row
->log_actor
: 0;
326 $userId = (int)$this->row
->log_user
;
327 if ( $userId !== 0 ||
$actorId !== 0 ) {
329 if ( isset( $this->row
->user_name
) ) {
330 $this->performer
= User
::newFromRow( $this->row
);
331 } elseif ( $actorId !== 0 ) {
332 $this->performer
= User
::newFromActorId( $actorId );
334 $this->performer
= User
::newFromId( $userId );
338 $userText = $this->row
->log_user_text
;
339 $this->performer
= User
::newFromName( $userText, false );
343 return $this->performer
;
346 public function getTarget() {
347 $namespace = $this->row
->log_namespace
;
348 $page = $this->row
->log_title
;
349 $title = Title
::makeTitle( $namespace, $page );
354 public function getTimestamp() {
355 return wfTimestamp( TS_MW
, $this->row
->log_timestamp
);
358 public function getComment() {
359 return CommentStore
::getStore()->getComment( 'log_comment', $this->row
)->text
;
362 public function getDeleted() {
363 return $this->row
->log_deleted
;
368 * A subclass of DatabaseLogEntry for objects constructed from entries in the
369 * recentchanges table (rather than the logging table).
371 class RCDatabaseLogEntry
extends DatabaseLogEntry
{
373 public function getId() {
374 return $this->row
->rc_logid
;
377 protected function getRawParameters() {
378 return $this->row
->rc_params
;
381 public function getAssociatedRevId() {
382 return $this->row
->rc_this_oldid
;
385 public function getType() {
386 return $this->row
->rc_log_type
;
389 public function getSubtype() {
390 return $this->row
->rc_log_action
;
393 public function getPerformer() {
394 if ( !$this->performer
) {
395 $actorId = isset( $this->row
->rc_actor
) ?
(int)$this->row
->rc_actor
: 0;
396 $userId = (int)$this->row
->rc_user
;
397 if ( $actorId !== 0 ) {
398 $this->performer
= User
::newFromActorId( $actorId );
399 } elseif ( $userId !== 0 ) {
400 $this->performer
= User
::newFromId( $userId );
402 $userText = $this->row
->rc_user_text
;
403 // Might be an IP, don't validate the username
404 $this->performer
= User
::newFromName( $userText, false );
408 return $this->performer
;
411 public function getTarget() {
412 $namespace = $this->row
->rc_namespace
;
413 $page = $this->row
->rc_title
;
414 $title = Title
::makeTitle( $namespace, $page );
419 public function getTimestamp() {
420 return wfTimestamp( TS_MW
, $this->row
->rc_timestamp
);
423 public function getComment() {
424 return CommentStore
::getStore()
425 // Legacy because the row may have used RecentChange::selectFields()
426 ->getCommentLegacy( wfGetDB( DB_REPLICA
), 'rc_comment', $this->row
)->text
;
429 public function getDeleted() {
430 return $this->row
->rc_deleted
;
435 * Class for creating new log entries and inserting them into the database.
439 class ManualLogEntry
extends LogEntryBase
{
440 /** @var string Type of log entry */
443 /** @var string Sub type of log entry */
446 /** @var array Parameters for log entry */
447 protected $parameters = [];
450 protected $relations = [];
452 /** @var User Performer of the action for the log entry */
453 protected $performer;
455 /** @var Title Target title for the log entry */
458 /** @var string Timestamp of creation of the log entry */
459 protected $timestamp;
461 /** @var string Comment for the log entry */
462 protected $comment = '';
464 /** @var int A rev id associated to the log entry */
465 protected $revId = 0;
467 /** @var string[] Change tags add to the log entry */
468 protected $tags = [];
470 /** @var int Deletion state of the log entry */
473 /** @var int ID of the log entry */
476 /** @var bool Can this log entry be patrolled? */
477 protected $isPatrollable = false;
479 /** @var bool Whether this is a legacy log entry */
480 protected $legacy = false;
484 * @param string $type
485 * @param string $subtype
487 public function __construct( $type, $subtype ) {
489 $this->subtype
= $subtype;
493 * Set extra log parameters.
495 * You can pass params to the log action message by prefixing the keys with
496 * a number and optional type, using colons to separate the fields. The
497 * numbering should start with number 4, the first three parameters are
498 * hardcoded for every message.
500 * If you want to store stuff that should not be available in messages, don't
501 * prefix the array key with a number and don't use the colons.
504 * $entry->setParameters(
505 * '4::color' => 'blue',
506 * '5:number:count' => 3000,
511 * @param array $parameters Associative array
513 public function setParameters( $parameters ) {
514 $this->parameters
= $parameters;
518 * Declare arbitrary tag/value relations to this log entry.
519 * These can be used to filter log entries later on.
521 * @param array $relations Map of (tag => (list of values|value))
524 public function setRelations( array $relations ) {
525 $this->relations
= $relations;
529 * Set the user that performed the action being logged.
532 * @param UserIdentity $performer
534 public function setPerformer( UserIdentity
$performer ) {
535 $this->performer
= User
::newFromIdentity( $performer );
539 * Set the title of the object changed.
542 * @param LinkTarget $target
544 public function setTarget( LinkTarget
$target ) {
545 $this->target
= Title
::newFromLinkTarget( $target );
549 * Set the timestamp of when the logged action took place.
552 * @param string $timestamp
554 public function setTimestamp( $timestamp ) {
555 $this->timestamp
= $timestamp;
559 * Set a comment associated with the action being logged.
562 * @param string $comment
564 public function setComment( $comment ) {
565 $this->comment
= $comment;
569 * Set an associated revision id.
571 * For example, the ID of the revision that was inserted to mark a page move
572 * or protection, file upload, etc.
577 public function setAssociatedRevId( $revId ) {
578 $this->revId
= $revId;
582 * Set change tags for the log entry.
584 * Passing `null` means the same as empty array,
585 * for compatibility with WikiPage::doUpdateRestrictions().
588 * @param string|string[]|null $tags
590 public function setTags( $tags ) {
591 if ( $tags === null ) {
593 } elseif ( is_string( $tags ) ) {
600 * Set whether this log entry should be made patrollable
601 * This shouldn't depend on config, only on whether there is full support
602 * in the software for patrolling this log entry.
606 * @param bool $patrollable
608 public function setIsPatrollable( $patrollable ) {
609 $this->isPatrollable
= (bool)$patrollable;
613 * Set the 'legacy' flag
616 * @param bool $legacy
618 public function setLegacy( $legacy ) {
619 $this->legacy
= $legacy;
623 * Set the 'deleted' flag.
626 * @param int $deleted One of LogPage::DELETED_* bitfield constants
628 public function setDeleted( $deleted ) {
629 $this->deleted
= $deleted;
633 * Insert the entry into the `logging` table.
635 * @param IDatabase|null $dbw
636 * @return int ID of the log entry
637 * @throws MWException
639 public function insert( IDatabase
$dbw = null ) {
640 global $wgActorTableSchemaMigrationStage;
642 $dbw = $dbw ?
: wfGetDB( DB_MASTER
);
644 if ( $this->timestamp
=== null ) {
645 $this->timestamp
= wfTimestampNow();
648 // Trim spaces on user supplied text
649 $comment = trim( $this->getComment() );
651 $params = $this->getParameters();
652 $relations = $this->relations
;
654 // Ensure actor relations are set
655 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) &&
656 empty( $relations['target_author_actor'] )
659 if ( !empty( $relations['target_author_id'] ) ) {
660 foreach ( $relations['target_author_id'] as $id ) {
661 $actorIds[] = User
::newFromId( $id )->getActorId( $dbw );
664 if ( !empty( $relations['target_author_ip'] ) ) {
665 foreach ( $relations['target_author_ip'] as $ip ) {
666 $actorIds[] = User
::newFromName( $ip, false )->getActorId( $dbw );
670 $relations['target_author_actor'] = $actorIds;
671 $params['authorActors'] = $actorIds;
674 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) ) {
675 unset( $relations['target_author_id'], $relations['target_author_ip'] );
676 unset( $params['authorIds'], $params['authorIPs'] );
679 // Additional fields for which there's no space in the database table schema
680 $revId = $this->getAssociatedRevId();
682 $params['associated_rev_id'] = $revId;
683 $relations['associated_rev_id'] = $revId;
687 'log_type' => $this->getType(),
688 'log_action' => $this->getSubtype(),
689 'log_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
690 'log_namespace' => $this->getTarget()->getNamespace(),
691 'log_title' => $this->getTarget()->getDBkey(),
692 'log_page' => $this->getTarget()->getArticleID(),
693 'log_params' => LogEntryBase
::makeParamBlob( $params ),
695 if ( isset( $this->deleted
) ) {
696 $data['log_deleted'] = $this->deleted
;
698 $data +
= CommentStore
::getStore()->insert( $dbw, 'log_comment', $comment );
699 $data +
= ActorMigration
::newMigration()
700 ->getInsertValues( $dbw, 'log_user', $this->getPerformer() );
702 $dbw->insert( 'logging', $data, __METHOD__
);
703 $this->id
= $dbw->insertId();
706 foreach ( $relations as $tag => $values ) {
707 if ( !strlen( $tag ) ) {
708 throw new MWException( "Got empty log search tag." );
711 if ( !is_array( $values ) ) {
712 $values = [ $values ];
715 foreach ( $values as $value ) {
718 'ls_value' => $value,
719 'ls_log_id' => $this->id
723 if ( count( $rows ) ) {
724 $dbw->insert( 'log_search', $rows, __METHOD__
, 'IGNORE' );
731 * Get a RecentChanges object for the log entry
734 * @return RecentChange
737 public function getRecentChange( $newId = 0 ) {
738 $formatter = LogFormatter
::newFromEntry( $this );
739 $context = RequestContext
::newExtraneousContext( $this->getTarget() );
740 $formatter->setContext( $context );
742 $logpage = SpecialPage
::getTitleFor( 'Log', $this->getType() );
743 $user = $this->getPerformer();
745 if ( $user->isAnon() ) {
746 // "MediaWiki default" and friends may have
747 // no IP address in their name
748 if ( IP
::isIPAddress( $user->getName() ) ) {
749 $ip = $user->getName();
753 return RecentChange
::newLogEntry(
754 $this->getTimestamp(),
757 $formatter->getPlainActionText(),
763 LogEntryBase
::makeParamBlob( $this->getParameters() ),
765 $formatter->getIRCActionComment(), // Used for IRC feeds
766 $this->getAssociatedRevId(), // Used for e.g. moves and uploads
767 $this->getIsPatrollable()
772 * Publish the log entry.
774 * @param int $newId Id of the log entry.
775 * @param string $to One of: rcandudp (default), rc, udp
777 public function publish( $newId, $to = 'rcandudp' ) {
778 DeferredUpdates
::addCallableUpdate(
779 function () use ( $newId, $to ) {
780 $log = new LogPage( $this->getType() );
781 if ( !$log->isRestricted() ) {
782 $rc = $this->getRecentChange( $newId );
784 if ( $to === 'rc' ||
$to === 'rcandudp' ) {
785 // save RC, passing tags so they are applied there
786 $rc->addTags( $this->getTags() );
787 $rc->save( $rc::SEND_NONE
);
789 $tags = $this->getTags();
791 $revId = $this->getAssociatedRevId(); // Use null if $revId is 0
792 ChangeTags
::addTags( $tags, null, $revId > 0 ?
$revId : null, $newId );
796 if ( $to === 'udp' ||
$to === 'rcandudp' ) {
797 $rc->notifyRCFeeds();
801 DeferredUpdates
::POSTSEND
,
806 public function getType() {
810 public function getSubtype() {
811 return $this->subtype
;
814 public function getParameters() {
815 return $this->parameters
;
821 public function getPerformer() {
822 return $this->performer
;
828 public function getTarget() {
829 return $this->target
;
832 public function getTimestamp() {
833 $ts = $this->timestamp ??
wfTimestampNow();
835 return wfTimestamp( TS_MW
, $ts );
838 public function getComment() {
839 return $this->comment
;
846 public function getAssociatedRevId() {
854 public function getTags() {
859 * Whether this log entry is patrollable
864 public function getIsPatrollable() {
865 return $this->isPatrollable
;
872 public function isLegacy() {
873 return $this->legacy
;
876 public function getDeleted() {
877 return (int)$this->deleted
;